package com.tbit.uqbike.client.validation;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Json校验器
 *
 *
 * @author <a href="mailto:chen.chaoxiong@tbit.com.cn">ChenChaoXiong</a>
 * @since 2024/7/2
 */
public class JsonValidator implements ConstraintValidator<IsValidJson, String> {

    @Override
    public void initialize(IsValidJson constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        try {
            if (StringUtils.isBlank(value)) {
                return true;
            }
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
